
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:map_launcher/map_launcher.dart';

import '../../../../utils/utils_dialog.dart';
import '../../../../utils/utils_logger.dart';
import '../../../../widgets/detail_item_widget/detail_item_view.dart';
import '../../../../widgets/globel_widget.dart';
import '../../../../widgets/group_choose_dialog/group_choose_dialog_view.dart';
import '../../../../widgets/spirit/spirit_view.dart';
import 'detail_logic.dart';

class DetailPage extends StatelessWidget {
  final logic = Get.put(DetailLogic());
  final state = Get.find<DetailLogic>().state;

  var managerOptController = Get.put(TextEditingController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          const Center(child: Text('Group1')),
          IconButton(
              key: GlobalKey(),
              icon: const Icon(Icons.add),
              tooltip: "添加分组",
              onPressed: () {
                print("添加分组--------------");
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return GroupChooseDialog(
                          selectPositionId: 1,
                          onSaveClick: () {
                            print("onSaveClick");
                          },
                          onGroupSelectChanged: (selected,index) {
                            print("onGroupSelectChanged $selected $index");
                          });
                    });
              }),
        ],
      ),
      body: Container(
        child: SingleChildScrollView(
          scrollDirection:Axis.vertical, // 滚动方向，默认是垂直方向
          child:Column(
            children: [
              spaceHeight(),
              buildSpiritComponent(),
              buildLine(),
              buildAdressComponent(context,"香港广东道1000号 广西大厦"),
              buildLine(),
              DetailItemComponent(
                  leftLabel: "故障时间",
                  leftText: "2023/06/28 12:23",
                  rightLabel: "故障代码",
                  rightText: "M23,M34"),
              buildLine(),
              DetailItemComponent(
                  leftLabel: "受理时间",
                  leftText: "2023/06/28 12:23",
                  rightLabel: "工程人员",
                  rightText: "M23,M34"),
              buildLine(),
              DetailItemComponent(
                  leftLabel: "工程人员确认时间",
                  leftText: "2023/06/28 12:23",
                  rightLabel: "工程人员确认",
                  rightText: "M23,M34"),
              buildLine(),
              DetailItemComponent(
                  leftLabel: "恢复时间",
                  leftText: "2023/06/28 12:23",
                  rightLabel: "人员确认",
                  rightText: "M23,M34"),
              buildLine(),
              buildEngineerOpt(),
              buildLine(),
              buildManagerOpt(managerOptController),
              buildLine(),
              buildGuidance()
            ],
          )
        ),
      ),
    );
  }

  ///电梯状态信息
  buildSpiritComponent() {
    return SpiritComponent(
      onTap: () {
        logd('onTap');
      },
      onLongPress: () {
        logd('onLongPress');
      },
      lLeftText: 'MS-L1',
      lRightText: '18/F',
      rLeftText: 'AL',
      rCenterText: 'PW',
      rLeftColor: Colors.red,
      rCenterColor: Colors.orange,
    );
  }

  ///电梯所在建筑物地址
  buildAdressComponent(BuildContext context,String? addres) {
    return Container(
        padding: const EdgeInsets.all(10),
        child: Row(children: [
          const Text("建筑物名称", style: TextStyle(fontSize: 16)),
          Flexible(
            child: Padding(
                padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: Container(
                    color: const Color(0xFFD6D6D6),
                    padding: const EdgeInsets.fromLTRB(1, 10, 1, 10),
                    child: Center(
                        child: Scrollbar(
                      child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Text(addres!,
                              maxLines: 1,
                              style: const TextStyle(fontSize: 14))),
                    )))),
          ),
          ElevatedButton(
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.black),
                backgroundColor:
                    MaterialStateProperty.all(const Color(0xFFBDBDBD)),
                textStyle:
                    MaterialStateProperty.all(const TextStyle(fontSize: 16)),
                overlayColor: MaterialStateProperty.all(Colors.blueGrey)),
            onPressed: () {
              openMapsSheet(context,addres,37.759392, -122.5107336);
            },
            child: const Text('MAP'), //选中的颜色字体颜色
          )
        ]));
  }

  openMapsSheet(context,String address,double x,double y) async {
    try {
      final coords = Coords(x, y);
      final title = address;
      final availableMaps = await MapLauncher.installedMaps;

      showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SafeArea(
            child: SingleChildScrollView(
              child: Container(
                child: Wrap(
                  children: <Widget>[
                    for (var map in availableMaps)
                      ListTile(
                        onTap: () => map.showMarker(
                          coords: coords,
                          title: title,
                        ),
                        title: Text(getLocalName(map: map)),
                        leading: SvgPicture.asset(
                          map.icon,
                          height: 30.0,
                          width: 30.0,
                        ),
                      ),
                  ],
                ),
              ),
            ),
          );
        },
      );
    } catch (e) {
      print(e);
    }
  }

  String getLocalName({required AvailableMap map}) {
    switch (map.mapType) {
      case MapType.apple:
        return '苹果地图';
      case MapType.amap:
        return '高德地图';
      case MapType.baidu:
        return '百度地图';
      case MapType.tencent:
        return '腾讯地图';
      case MapType.google:
        return '谷歌地图';
      default:
        return map.mapName;
    }
  }

  buildLine() {
    return Container(
      child: Column(
        children: [
          spaceHeight(),
          Container(
            color: Colors.grey,
            height: 1,
          ),
          spaceHeight(),
        ],
      ),
    );
  }

  ///构建工程人员操作
  buildEngineerOpt() {
    return Container(
        color: const Color(0xFFD6D6D6),
        padding: const EdgeInsets.all(10),
        child: Row(children: [
          const Text("工程人操作", style: TextStyle(fontSize: 16)),
          Flexible(
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(
                    style: ButtonStyle(
                        foregroundColor:
                            MaterialStateProperty.all(Colors.amber),
                        backgroundColor:
                            MaterialStateProperty.all(const Color(0xFF757575)),
                        textStyle: MaterialStateProperty.all(
                            const TextStyle(fontSize: 16)),
                        overlayColor:
                            MaterialStateProperty.all(Colors.blueGrey)),
                    onPressed: () {
                      print("Search Pressed");
                    },
                    child: const Text('受理确认'), //选中的颜色字体颜色
                  ),
                  ElevatedButton(
                    style: ButtonStyle(
                        foregroundColor:
                            MaterialStateProperty.all(Colors.green),
                        backgroundColor:
                            MaterialStateProperty.all(const Color(0xFFBDBDBD)),
                        textStyle: MaterialStateProperty.all(
                            const TextStyle(fontSize: 16)),
                        overlayColor:
                            MaterialStateProperty.all(Colors.blueGrey)),
                    onPressed: () {
                      print("Search Pressed");
                    },
                    child: const Text('恢复确认'), //选中的颜色字体颜色
                  )
                ]),
          )
        ]));
  }

  buildManagerOpt(TextEditingController? managerOptController) {
    return Container(
      padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
      child: Row(children: [
          const Text("管理人操作", style: TextStyle(fontSize: 16)),
          Flexible(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
              child: Container(
                  color: const Color(0xFFD6D6D6),
                  padding: const EdgeInsets.fromLTRB(1, 10, 1, 10),
                  child: Center(
                      child: TextField(
                        controller: managerOptController,
                        decoration: null,
                        style: const TextStyle(fontSize: 16),
                        keyboardType: TextInputType.text,
                      )))),
          ),
        ElevatedButton(
            style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all(Colors.black),
                backgroundColor:
                MaterialStateProperty.all(const Color(0xFFBDBDBD)),
                textStyle:
                MaterialStateProperty.all(const TextStyle(fontSize: 16)),
                overlayColor: MaterialStateProperty.all(Colors.blueGrey)),
            onPressed: () {
              print("Search Pressed");
            },
        child: const Text('发送')),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
            children:[
          Container(height: 20,child:const Text("AUTO", style: TextStyle(fontSize: 16))),
              Container(height: 20,child:Obx(() => Checkbox(
              value: logic.state.isAutoSendMsg.value,
              onChanged: (value) => logic.changeAutoSendChecked(value!))))
        ])
    ])
    );
  }

  ///故障处理指导
  buildGuidance() {
    return Container(
        margin: const EdgeInsets.all(10),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          const Text("故障处理指导", style: TextStyle(fontSize: 16)),
          Container(
              color: const Color(0xFFD6D6D6),
              padding: const EdgeInsets.all(10),
              child: Center(
                  child: TextField(
                controller: managerOptController,
                decoration: null,
                minLines: 4,
                maxLines: 200,
                style: const TextStyle(fontSize: 16),
                keyboardType: TextInputType.text,
              )))
        ]));
  }

  Future<void> showModGroupDialog(BuildContext context, Offset? anchorPoint) {
    return showAnchorPointDialog(context, anchorPoint: anchorPoint, builder: (BuildContext context) {
      return Material(
        color: Colors.transparent,
        child: WillPopScope(
          onWillPop: () => Future.value(false),
          child: Center(
            child: Container(
              width: 200.0,
              height: 200.0,
              padding: const EdgeInsets.all(4.0),
              decoration: const BoxDecoration(
                //背景装饰
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(4.0)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  const Padding(
                    padding: EdgeInsets.all(10),
                    child: Text("添加/删除组（Group）"),
                  ),
                  Row(
                    children: List<Widget>.generate(
                      5,
                          (int index) {
                        return ChoiceChip(
                          label: Text('$index'),
                          selected: state.selectGroup.value == index,
                          onSelected: (bool selected) {
                            logic.selectGroup(selected,index);
                          },
                        );
                      },
                    ).toList(),
                  )
                ],
              ),
            ),
          ),
        ),
      );
    });
  }

  buildGroupCheck(bool value,ValueChanged<bool?>? onChangedLisener) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children:[
        Container(height: 20,
          child:const Text("3", style: TextStyle(fontSize: 16))
        ),
        Container(height: 20,
            child:Checkbox(
              value: true,
              onChanged: (value) => onChangedLisener)
        )
      ]
    );
  }

  Future<T?> showAnchorPointDialog<T>(BuildContext context,
      {bool barrierDismissible = true, Offset? anchorPoint,WidgetBuilder? builder}) {
    return showDialog<T?>(
        context: context,
        barrierDismissible: barrierDismissible,
        anchorPoint: anchorPoint,
        builder: (context) {
          return MediaQuery(
            //不受系统字体缩放影响
            data: MediaQueryData.fromView(View.of(context))
                .copyWith(textScaleFactor: 1),
            child: SafeArea(
              child: builder!(context),
            ),
          );
        });
  }
}
